//
//  TFUITextTabPageViewController.m
//  TFFoundation
//
//  Created by 夏之祥 on 2019/5/7.
//

#import "TFUITextTabPageViewController.h"
#import <Masonry/Masonry.h>

@interface TFUITextTabPageViewController ()<TFUITabViewDelegate>

@property(nonatomic, strong, readwrite) TFUITextTabView *tabView;

@end

@implementation TFUITextTabPageViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self didInitialize];
    }
    return self;
}

- (void)didInitialize {
    self.tabViewHeight = 40.0;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view addSubview:self.tabView];
    
    [_tabView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0.0);
        make.top.mas_equalTo(self.view.mas_topMargin);
        make.height.mas_equalTo(self.tabViewHeight);
    }];
    [self.containerController.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.tabView);
        make.top.mas_equalTo(self.tabView.mas_bottom);
        make.bottom.mas_equalTo(0.0);
    }];
}

- (NSInteger)numbersOfPage {
    return self.tabView.dataSourceArray.count;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.tabView associatedScrollView:scrollView contentOffsetDidChange:[self p_getFixedPageControllerScrollViewContentOffsetWithScrollView:scrollView]];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    NSInteger index = [self p_getFixedPageControllerScrollViewContentOffsetWithScrollView:scrollView].x/CGRectGetWidth(scrollView.frame);
    [self.tabView selectTabAtIndex:index animated:NO];
}

- (CGPoint)p_getFixedPageControllerScrollViewContentOffsetWithScrollView:(UIScrollView *)scrollView {
    CGFloat scrollViewWidth = CGRectGetWidth(scrollView.frame);
    CGPoint contentOffset = CGPointMake(self.currentPage*scrollViewWidth + scrollView.contentOffset.x - scrollViewWidth, 0);
    return contentOffset;
}

#pragma mark - TFUITextTabViewDelegate

- (void)tabView:(TFUITabView *)tabView didSelectTabAtIndex:(NSInteger)index animated:(BOOL)animated {
    [self selectPage:index animated:animated];
}

#pragma mark - lazy load.

- (TFUITextTabView *)tabView {
    if (!_tabView) {
        _tabView = [[TFUITextTabView alloc] init];
        _tabView.delegate = self;
    }
    return _tabView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
